<?php

namespace app\index\controller;

use think\Controller;
use think\Lang;
use think\Request;
use org\Agent;
use org\Ip;

class Base extends Controller
{

    protected $template, $system, $datas, $url;

    public function _initialize()
    {

        /*显示导航-首页*/
        //        $ss = allow_release_arctype_index();
        //        dump($ss);
        //        exit();
        /*显示导航-首页end*/
        /**
         * 根据ip获取城市、网络运营商等信息
         */

        /*
        $taobaodata = cache('\'' . $this->request->ip() . '\'');
        if (empty($taobaodata)) {
            $taobaodata = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $this->request->ip());
            $taobaodata = json_decode($taobaodata, $assoc = true);

            cache('\'' . $this->request->ip() . '\'', $taobaodata);
        }
        if($taobaodata){
            $data['dizhi'] = $taobaodata['data']['country'] . $taobaodata['data']['region'] . $taobaodata['data']['city'];
            $data['ip'] = $taobaodata['data']['ip'];
            $data['lang'] = $taobaodata['data']['country_id'];
        }
        */


        $browsertype = $this->browsertype();
        $this->datas['status'] = '1';
        $this->datas['lang'] = cookie('think_var');
        $new = md5($this->request->ip() . $browsertype . cookie('think_var'));
        $iptime = cache($new);
        if (empty($iptime)) {
            cache($new, 'true', 240);
            $data['dizhi'] = implode(" ", Ip::find($this->request->ip()));
            $data['ip'] = $this->request->ip();

            $http = $this->request->server('HTTP_REFERER');
            if (!empty($http)) {
                $key = keytype($http);
                if ($key) {
                    $data['antepage'] = $key['1'];
                    $data['network'] = $key['0'];
                }
                $url = $http;
            } else {
                $url = $this->request->url(true);
            }
            //添加浏览人数
            db('system')->where('title', 'const')->where('lang', $this->datas['lang'])->setInc('value');
            $data['visitpage'] = $url;
            //        $browser = getbrowser();
            $data['browser'] = Agent::getBroswer(); //$browser['bro'];
            $data['sys'] = Agent::getOs(); //$browser['sys'];
            $data['browsertype'] = $browsertype;
            model('VisitSummary')->allowField(true)->save($data);
        }
        //记录浏览人数
        $const = db('system')->where('title', 'const')->where('lang', $this->datas['lang'])->value('value');
        //        $dirname = $this->request->module() == 'index' ? 'pc' : 'mobile';
        $dirname = 'pc';
        $this->template = APP_PATH . request()->module() . '/../../template/' . $dirname . DS . cache('systemsystem' . cookie('think_var'))[$dirname . 'template']['value'] . DS;
        $navid = $this->request->param('navid');
        $navid = $navid ? $navid : '0';

        $this->assign([
            'link' => cache('link' . cookie('think_var')),
            'lang' => cookie('think_var'),
            'navid' => $navid,
            'const' => $const,
            'Requestcontroller' => $this->Requestcontroller(),
            'browsertype' => $browsertype,
            // 'nav_model' => config('nav.nav_type'),2019-04-24 不知道有什么用
            'empty' => lang('No relevant data'),
        ]);
    }

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->url = $this->request->module() == 'mobile' ? '/mobile' : '';
        $this->url = $this->request->domain() . $this->url;
        //头部导航
        $navs = model('nav')->catenav($this->datas);

        $json_navs = json_encode($navs);
 
        $adindex = model('adindex')->where($this->datas)->cache(true)->column('url,title,image,center', 'position');

        // 用标签显示
         $online = model('online')
             ->where($this->datas)
            ->cache(true)
             ->select();
        
        //头部幻灯片
        $browsertype = $this->browsertype();
        $navid = $this->request->param('navid');
        $navid = $navid ? $navid : '0';
        $cahe = $browsertype . $navid . cookie('think_var');
        $carousel = cache($cahe);
        if (empty($carousel)) {
            $where = null;
            $where['model'] = $browsertype;
            isset($navid) ? $where['type'] = ['like', '%,' . $navid . ',%'] : '';
            $carousel = model('carousel')
                ->where($where)
                ->where($this->datas)
                ->order('sort DESC')
                ->cache(true)
                ->select();
            cache($cahe, $carousel);
        }

        //内容幻灯片
        $centerturn = cache('turn' . $cahe);
        if (empty($centerturn)) {
            $where = null;
            isset($navid) ? $where['type'] = ['like', '%,' . $navid . ',%'] : '';
            $centerturn = model('centerturn')->where($where)->where($this->datas)->order('sort deSC')->limit(4)->select();
            cache('turn' . $cahe, $centerturn);
        }
// dump($carousel);
        $this->assign([
            'carousel' => $carousel,
            'adindex' => $adindex,
            'centerturn' => $centerturn,
             'online' => $online,
            'json_navs' => $json_navs,
            'nav' => $navs,
            'system' => cache('systemsystem' . cookie('think_var')),
        ]);
    }


    protected $beforeActionList = [
        'right' => ['only' => 'index,detailed'],
    ];

    public function index($navid = null)
    {
        $post = $this->request->param();


        if (empty($navid)) {
            if (isset($post['comid'])) {
                //更多页面
                $datas['status'] = '1';
                $datas['comid'] = $post['comid'];
                $datas['lang'] = cookie('think_var');
                $list = db('article')
                    ->where($datas)
                    ->order('sort DESC,id DESC')
                    ->paginate()
                    ->appends($this->request->param());
                $this->assign('list', $list);
                $this->assign('comname', db('company')->where('id', $post['comid'])->field('title,id')->find());

                return $this->fetch($this->template . 'article.html');
                exit();
            }
            $this->redirect($this->url);
            //            $this->error('参数错误');
        }

        /*栏目详情start*/
        $cateInfo = db('nav')->where('id', $navid)->where($this->datas)->cache(60)->find();

        if (empty($cateInfo)) {
            if (!empty($post['navid'])) {
                $this->morelang();
            }
            $this->redirect($this->url);
            //$this->error('栏目不存在');
        }

        /*栏目详情end*/
        $this->assign('cateInfo', $cateInfo);

        /*模板start*/
        if ($cateInfo['type'] == 'one') {
            $res = db('nav')
                ->field('c.id')
                ->alias('c')
                ->join('__NAV__ s', 's.pid = c.id', 'right ')
                ->where('c.id', $navid)
                ->group('c.id')
                ->order('s.id asc')
                ->cache(true)
                ->find();
            //单页面显示页
            if (!empty($res)) {
                $cateInfo_new = db('nav')
                    ->where('pid', $navid)
                    ->where($this->datas)
                    ->order('sort ASC')
                    ->cache(true)
                    ->find();
                if (!empty($cateInfo_new)) {
                    return $this->index($cateInfo_new['id']);
                }
            }

            /*文章列表end*/
            return $this->fetch($this->template . $cateInfo['temppage']);
        } else {
            if ($cateInfo['pid']) {
                $list = cache($cateInfo['id'] . $this->request->param('page') . $this->request->module() . cookie('think_var'));
                if (empty($list_junqu)) {
                    /*所有数据列表start*/
                    $list = db($cateInfo['model'])->alias('a')
                        ->join('__NAV__ c', 'c.id= a.cid')
                        ->field('a.*,c.name,c.model')
                        ->where('c.status', '1')
                        ->where('a.status', '1')
                        ->where('a.lang = c.lang')
                        ->where('a.lang', cookie('think_var'))
                        ->order('a.sort DESC,a.id DESC')
                        ->where('c.id', $navid)
                        ->paginate()
                        ->appends($this->request->param());

                    cache($cateInfo['id'] . $this->request->param('page') . $this->request->module() . cookie('think_var'), $list);
                }
            } else {
                /*列表start*/
                /*
                $list = cache($cateInfo['id'] . $this->request->param('page') . $this->request->module() . cookie('think_var'));
                if (empty($list_junqu)) {
                    $list = db($cateInfo['model'])->alias('a')
                        ->join('__NAV__ c', 'c.id = a.cid')
                        ->field('a.*,c.name,c.model')
                        ->where('c.status', '1')
                        ->where('c.model', $cateInfo['model'])
                        ->where('a.status', '1')
                        ->where('a.lang = c.lang')
                        ->where('a.lang', cookie('think_var'))
                        ->order('a.sort DESC,a.id DESC')
                        ->where('c.pids', 'like', '%,' . $navid . ',%')
                        ->paginate()
                        ->appends($this->request->param());
                    cache($cateInfo['id'] . $this->request->param('page') . $this->request->module() . cookie('think_var'), $list);
                }*/

                //最新
                $arctype_list = $this->getHasChildren($cateInfo['id']);
                foreach ($arctype_list as $key => $val) {
                    if ($cateInfo['model'] != $val['model']) {
                        unset($arctype_list[$key]);
                    }
                }

                $typeids = get_arr_column($arctype_list, "id");
                $typeids[] = $cateInfo['id'];
                $typeid = implode(",", $typeids);

                $typeid = "cid IN ({$typeid})";
                $list = db($cateInfo['model'])->where($typeid)
                    ->where('status', '1')
                    ->order('sort DESC,id DESC')
					->cache(60)
                    ->paginate()
                    ->appends($this->request->param());
            }

            $this->assign('list', $list);
            /*列表end*/
            return $this->fetch($this->template . $cateInfo['templist']);
        }
        /*模板end*/
    }


    public function detailed($id)
    {
        //显示内容
        $model = $this->request->controller();
        $data = cache($model . $id);
        if (empty($data_junqu)) {
            $datas = array();
            $Admin = session('Admin', '', 'admin');
            if (!empty($Admin)) {
                unset($this->datas['status']);
            }

            $data = model($model)->where($this->datas)->where($datas)->cache(120)->find($id);
            cache($model . $id, $data);
        }
        model($model)->where('id', $data['id'])->setInc('hits', 1);
        //投稿的内容
        if (!empty($data['contribute'])) {
            //更多页面
            !empty($data['comid']) ? $datas['comid'] = $data['comid'] : '';
            $datas['status'] = '1';
            $datas['comid'] = $datas['comid'];
            $datas['lang'] = cookie('think_var');
            $next = model($model)->getnext($id, $datas);
            $this->assign('data', $data);
            $this->assign('next', $next);
            $this->assign('comname', db('company')->where('id', $data['comid'])->field('title,id')->find());
            return $this->fetch($this->template . 'articledetailed.html');
        } else {

            $cateInfo = db('nav')->where('id', $data['cid'])->where($this->datas)->find();

            if (!$cateInfo) {
                $this->morelang();
                $this->redirect($this->url);
                //$this->error(Lang::get('error'));
            }

            //更多页面
            !empty($data['cid']) ? $datas['cid'] = $data['cid'] : '';
            $datas['status'] = '1';
            $datas['lang'] = cookie('think_var');
            $next = model($model)->getnext($id, $datas);
            $this->assign('data', $data);
            $this->assign('cateInfo', $cateInfo);
            $this->assign('next', $next);
            return $this->fetch($this->template . $cateInfo['temparticle']);
        }
    }

    /**
     * 自动跳转多语言页面
     */
    public function morelang()
    {
        $lang = model('nav')->where(['id' =>$this->request->param('navid')])->cache(true)->value('lang');
        if ($lang != cookie('think_var') && $lang) {
            cookie('think_var', $lang);
            $this->redirect($this->request->url(true));
        }
    }

    /**
     * 更多页面
     */
    public function more()
    {
        $table = $this->request->controller();
        $list = model($table)->where($this->datas)->paginate();
        $reight_nav = model('nav')->where('model', $table)->where($this->datas)->cache(true)->select();

        $this->assign([
            'list' => $list,
            'table' => $table,
            'reight_nav' => $reight_nav,
            'fname_nav' => Lang::get('All class'),
            'empty' => lang('No relevant data'),
        ]);
        return $this->fetch($this->template . 'more.html');
    }

    /**
     * 返回用户浏览时的设备端
     * return pc,mobile
     */
    public function browsertype()
    {
        if (Request::instance()->isMobile()) {
            $browsertype = 'mobile';
        } else {
            $browsertype = 'pc';
        }
        return $browsertype;
    }

    
    /**
     * 返回用户浏览时的设备端
     * return pc,mobile
     */
    public function Requestcontroller()
    {
        if (Request::instance()->controller() =='About') {
            $Request_controller = 'Index';
        } else {
            $Request_controller = Request::instance()->controller();
        }
        return $Request_controller;
    }

    //新的左边导航
    public function right()
    {
        $data = array();

        $typeid = $cache = $this->request->param('navid');
        $map = array(
            'lang' => cookie('think_var'),
            'status' => 1
        );
        $cacheKey = md5($typeid);
        $sonRow = cache($cacheKey);
        if (empty($sonRow)) {
            $nav_list = model('nav')->where($map)->column('*', 'id');
            if (isset($nav_list[$typeid])) {
                // 第一个先装起来
                //            $nav_list[$typeid]['typeurl'] = $this->getTypeUrl($nav_list[$typeid]);
                $data[$typeid] = $nav_list[$typeid];
            } else {
                return false;
            }
            while (true) {
                @$typeid = $nav_list[$typeid]['pid'];
                if ($typeid > 0) {
                    if (isset($nav_list[$typeid])) {
                        $data[$typeid] = $nav_list[$typeid];
                    }
                } else {
                    break;
                }
            }
            $row = array_reverse($data, true);

            if (!empty($row)) {
                reset($row); // 重置排序
                $firstResult = current($row); // 顶级栏目下的第一级父栏目
                $typeid = isset($firstResult['id']) ? $firstResult['id'] : '';
                $sonRow = $this->getSon($typeid, false); // 获取第一级栏目下的子孙栏目，为空时不获得同级栏目
            }

            $fname_nav = isset($nav_list[$typeid]['name']) ? $nav_list[$typeid]['name'] : '';
            cache($cacheKey . $cache, $fname_nav);
            cache($cacheKey, $sonRow);
        }


        // echo $fname_nav = isset($nav_list[$typeid]['name']) ? $nav_list[$typeid]['name'] : '';
        $this->assign('reight_nav', $sonRow);
        $this->assign('fname_nav', cache($cacheKey . $cache));
    }

    /**
     * 获取下一级栏目
     * @param string $self true表示没有子栏目时，获取同级栏目
     * @author wengxianhu by 2017-7-26
     */
    public function getSon($typeid, $self = false)
    {
        $result = array();
        if (empty($typeid)) {
            return $result;
        }
        $nav_max_level = intval(3); // 栏目最多级别
        /*获取所有显示且有效的栏目列表*/
        $map = array(
            'c.status' => 1,
        );
        $fields = "c.*, c.id as typeid, count(s.id) as has_children, '' as list";

        $res = db('nav')
            ->field($fields)
            ->alias('c')
            ->join('__NAV__ s', 's.pid = c.id', 'LEFT')
            ->where($map)
            //            ->where('c.lang', $this->home_lang)
            ->group('c.id')
            ->order('c.pid asc, c.sort asc, c.id')
            ->cache(true, 600, "nav")
            ->select();
        /*--end*/

        /*栏目层级归类成阶梯式*/
        $arr = group_same_key($res, 'pid');

        for ($i = 0; $i < $nav_max_level; $i++) {
            foreach ($arr as $key => $val) {
                foreach ($arr[$key] as $key2 => $val2) {
                    if (!isset($arr[$val2['id']])) continue;
                    //原来的数组名称    $val2['children'] = $arr[$val2['id']];
                    $val2['list'] = $arr[$val2['id']];
                    $arr[$key][$key2] = $val2;
                }
            }
        }

        /*--end*/
        /*取得指定栏目ID对应的阶梯式所有子孙等栏目*/
        $result = array();
        $typeidArr = explode(',', $typeid);
        foreach ($typeidArr as $key => $val) {
            if (!isset($arr[$val])) continue;
            if (is_array($arr[$val])) {
                foreach ($arr[$val] as $key2 => $val2) {
                    array_push($result, $val2);
                }
            } else {
                array_push($result, $arr[$val]);
            }
        }
        /*--end*/

        return $result;
    }

    /**
     * 获取当前栏目及所有子栏目
     * @param boolean $self 包括自己本身
     * @author wengxianhu by 2017-7-26
     */
    public function getHasChildren($id, $self = true)
    {
        $lang = cookie('think_var'); // 多语言
        $cacheKey = "common_model_Arctype_getHasChildren_{$id}_{$self}_{$lang}";
        $result = cache($cacheKey);
        if (empty($result)) {
            $where = array(
                'c.status'  => 1,
                'c.lang'    => $lang,
            );
            $fields = "c.*, count(s.id) as has_children";
            $res = db('nav')
                ->field($fields)
                ->alias('c')
                ->join('__NAV__ s', 's.pid = c.id', 'LEFT')
                ->where($where)
                ->group('c.id')
                ->order('c.pid asc, c.sort asc, c.id')
                ->select();

            $result = arctype_options($id, $res, 'id', 'pid');

            if (!$self) {
                array_shift($result);
            }

            cache($cacheKey, $result, null, "arctype");
        }

        return $result;
    }


    //左边导航——旧
    public function right__()
    {
        $pid = model('nav')->where('id', $this->request->param('navid'))->where($this->datas)->cache(true)->value('pid');
        $pid = !empty($pid) ? $pid : $this->request->param('navid');

        $reight_nav = cache('right' . $pid . cookie('think_var'));
        if (empty($reight_nav)) {
            $reight_nav = model('nav')
                ->field('pid,id,type,name,model,link')
                ->where('pid', $pid)
                ->where($this->datas)
                ->order('sort asc,id ASC')
                ->select();
            foreach ($reight_nav as $k => $v) {
                $reight_nav[$k]['list'] = model('nav')
                    ->field('pid,id,type,name,model,link')
                    ->where('pid', $v['id'])
                    ->where($this->datas)
                    ->order('sort asc,id ASC')
                    ->select();
            }
            $reight_nav = $reight_nav ? $reight_nav : 'null';
            cache('right' . $pid . cookie('think_var'), $reight_nav);
        }

        $id = !empty($reight_nav[0]['pid']) ? $reight_nav[0]['pid'] : $this->request->param('navid');
        $fname_nav = model('nav')->where('id', $id)->where($this->datas)->cache(true)->value('name');

        $this->assign('reight_nav', $reight_nav);
        $this->assign('fname_nav', $fname_nav);
    }

    //左边导航_备份
    public function right_bloak()
    {

        $pid = model('nav')->where('id', $this->request->param('navid'))->where($this->datas)->cache(120)->value('pid');
        $pid = !empty($pid) ? $pid : $this->request->param('navid');
        $reight_nav = model('nav')
            ->where('pids', 'like', '%,' . $pid . ',%')
            ->where($this->datas)
            ->whereNotIn('id', $this->request->param('navid'))
            ->order('sort asc,id ASC')
            ->select();
        $this->assign('reight_nav', $reight_nav);
    }
}
